package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.DatabaseException;
import model.LoginModel;
import model.User;

/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();
//		System.out.println("The username is: "+username);
//		System.out.println("The password is: "+password);
		PrintWriter out = response.getWriter();
		if(username!=null && username.equals("admin") && password!=null && password.equals("admin")){
			try {
				boolean adminAccountExists = LoginModel.isThereAdminAccount();
				if(adminAccountExists){
					out.print("No such user");
					return;
				}
				User user = new User(-1, "admin", "admin", null, null, null, null, null, "A");
				session.setAttribute("user", user);
				out.print("Administration.html");
				return;
				
			} catch (DatabaseException e) {
				//problem with DB
				out.print("TechnicalDifficulties.html");
			}
		}
		
		try {
			Optional<User> optionalUser = LoginModel.getUser(username, password);
			if(optionalUser.isPresent()){
//				System.out.println("User is present!");
				User user = optionalUser.get();
				
				session.setAttribute("user", user);
				String accountType = user.getAccountType();
				switch (accountType) {
				case "A": out.print("Administration.html");
					break;
				case "S": out.print("Supplier.html");
					break;
				default: {out.print("index.html"); } 
					break;
				}
			}else{
				//no such user
				out.print("No such user");
			}
		} catch (DatabaseException e) {
			//problem with DB
			out.print("TechnicalDifficulties.html");
		}

	}

}
